package com.freedom.sql.jdbc.request;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.sql.jdbc.netty.MyNioSocketChannel;
import com.freedom.sql.jdbc.pool.socket.MySocket;
import com.freedom.sql.jdbc.response.CommonOkPacket;
import com.freedom.sql.jdbc.utils.ByteUtils;
import com.freedom.sql.jdbc.utils.MyJsonProperties;

public class UseDatabasePacket {
	@SuppressWarnings("unused")
	private static final Logger logger = LogManager.getLogger(UseDatabasePacket.class);
	private MyNioSocketChannel channel;
	private String content;
	private int packetSeq;

	public UseDatabasePacket(int _packetSeq, MyNioSocketChannel _channel, String _content) {
		packetSeq = _packetSeq;
		channel = _channel;
		content = _content;
	}

	public void read() throws Exception {
		// 开始处理,发送数据库给client
		if (null == MyJsonProperties.getInstance().getDatabases().get(content)) {
			throw new Exception("invalid db [" + content + "]");
		}
		String oldDB = channel.getDb();
		if (null == oldDB) {
			channel.setDb(content);
			new CommonOkPacket(channel, packetSeq + 1).write();
		} else if (oldDB.equals(content)) {
			new CommonOkPacket(channel, packetSeq + 1).write();
		} else {
			throw new Exception("not allowed to change db [" + oldDB + "->" + content + "]");
		}
	}

	// 写write
	private MySocket writeSocket;
	private String db;

	public UseDatabasePacket(MySocket s, String _db) {
		this.writeSocket = s;
		this.db = _db;
	}

	public void write() throws IOException {
		byte[] headerLen = null;
		byte[] packetSeq = new byte[] { 0x00 };
		byte[] type = new byte[] { 0x02 };
		byte[] dbBytes = ByteUtils.encode(db, "utf8");
		headerLen = ByteUtils.writeInt(1 + dbBytes.length, 3);
		OutputStream out = writeSocket.getChannel().getOutputStream();
		out.write(headerLen);
		out.write(packetSeq);
		out.write(type);
		out.write(dbBytes);
	}
}
